package com.javandad.app.server.servlet;

import java.util.Date;

import javax.jdo.JDOException;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.javandad.app.client.profile.ProfileService;
import com.javandad.app.server.UserManager;
import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.server.mail.MailHandler;
import com.javandad.app.server.mail.entity.WelcomeMail;
import com.javandad.app.shared.entity.User;

@SuppressWarnings("serial")
public class ProfileServlet extends RemoteServiceServlet implements ProfileService {
	
	static DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();

	@Override
	public String registerNewUser(final User newUser) {
		if(userExists(newUser.getUsername()))
		{
			String err = "user "+newUser.getUsername()+" already exists";
			System.out.println(err);
			return err;
		}
		
		newUser.setCreationDate(new Date());
		PersistenceManager pm = PMFSingleton.getPM();
		try
		{
			pm.makePersistent(newUser);
			MailHandler.sendMail(new WelcomeMail(newUser));
			login(newUser);
			return null;
		}
		catch(JDOException e)
		{
			return "Error adding user "+newUser+":\n"+e.getMessage();
		}
		finally
		{
			pm.close();
		}
	}
	
	private void login(User user) {
		HttpServletRequest request = this.getThreadLocalRequest();
		HttpSession session = request.getSession();
		session.setAttribute("mode", "1");
		session.setAttribute("username", user.getUsername());
		session.setAttribute("user", user);
	}

	public boolean userExists(String username)
	{
		PersistenceManager pm = PMFSingleton.getPM();
		User exists = null;
		try
		{
			exists = pm.getObjectById(User.class, username);
		}
		catch(JDOObjectNotFoundException e)
		{
			System.out.println(e.getMessage());
		}
		finally
		{
			pm.close();
		}
		return (exists != null);
	}

	@Override
	public User getUser() {
		PersistenceManager pm = PMFSingleton.getPM();
		User user = UserManager.getCurrentUser(pm);
		pm.close();
		return user;
	}
	
	@Override
	public User getUser(String username) {
		PersistenceManager pm = PMFSingleton.getPM();
		User user = dbm.getUser(username, pm);
		pm.close();
		return user;
	}

	@Override
	public boolean changeUser(User changedUser) {
		PersistenceManager pm = PMFSingleton.getPM();
		try
		{
			pm.makePersistent(changedUser);
			return true;
		}
		catch(JDOException e)
		{
			return false;
		}
		finally
		{
			pm.close();
		}
	}

}
